package com.jnc.rest.core.des.advice;

import com.jnc.rest.core.des.annotation.Decrypt;
import com.jnc.rest.core.des.auto.EncryptProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @Auther: jjn
 * @Date: 2020/2/13 14:20
 * @Desc: 请求参数接收处理类
 * 1、对加了@Decrypt的方法的数据进行解密操作
 * 2、只对@RequestBody参数有效
 */
@Slf4j
@ControllerAdvice
public class DecryptRequestBodyAdvice implements RequestBodyAdvice {

    @Autowired
    private EncryptProperties encryptProperties;

    @Override
    public boolean supports(MethodParameter methodParameter, Type type,
                            Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter,
                                           Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        if(methodParameter.getMethod().isAnnotationPresent(Decrypt.class) && encryptProperties.isOpen()){
            try {
                return new DecryptHttpInputMessage(httpInputMessage, encryptProperties.getSalt(), encryptProperties.getCharset());
            } catch (Exception e) {
                log.error("param decrypt error, method: {}, exception: {}", methodParameter.getMethod().getName(), e);
                throw new IllegalArgumentException();
            }
        }
        return httpInputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage httpInputMessage,
                                MethodParameter methodParameter, Type type,
                                Class<? extends HttpMessageConverter<?>> aClass) {
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter,
                                  Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return body;
    }
}
